/**
* Class to manage a generic function to be executed in the Servlet
*
* Project: idbcrown
* Author:  TM
* Date:    22/12/2012
*
* History
* ------------------
* 22/12/2012 - TM - Initial version.
*/
 
 
package Functions;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import Application.*;
import Util.*;

public abstract class genericFunction
{
    /** Constants */
    protected static final String ERROR = "Error: 404";
    protected static String lastSubSession;
    /** Class attributes */
    protected HttpServletRequest  request;
    protected HttpServletResponse response;
    protected PrintWriter         out;
    protected boolean             returnHTML = true;
    protected String              subSession;
    
    /** Constructor that does not retrieve HTML */
    public genericFunction(HttpServletRequest _request, HttpServletResponse _response) throws IOException, ServletException
    {
       this(_request, _response, false);
    }

    /** Constructor  */
    public genericFunction(HttpServletRequest _request, HttpServletResponse _response, boolean isHTMLReturned) throws IOException, ServletException
    {
       request  = _request;
       response = _response;
       response.setContentType("text/html");
       out        = response.getWriter();
       returnHTML = isHTMLReturned;
       createFunctionSession();
    }
    
    //Own methods

    /** Calculates subSession for current function call */
    public void createFunctionSession()
    {
       try
       {
         subSession = "" + System.currentTimeMillis();
         if ((lastSubSession != null) && (lastSubSession.equals(subSession)))
         {
           while (lastSubSession.equals(subSession))
           {
             subSession = "" + System.currentTimeMillis();
             Thread.sleep(100);           
           }
         }
         
         lastSubSession = subSession;
       }
       catch(Exception ex)
       {
         sendError(ex);
       }
    }
    
    //Abstract methods
    
    /** Execute function */
    public abstract String execute();
    
    //Getters
    public HttpServletRequest  getRequest()   {return request;}
    public HttpServletResponse getResponse()  {return response;}
    public boolean             returnHTML ()  {return returnHTML;}
    public String              getSession ()  {return subSession;}
    

    /** Sends response for error */
    public void sendError()
    {
       sendResponse(ERROR);
    }

    /** Sends response for error with exception */
    public void sendError(Exception ex)
    {
       sendResponse(ERROR+ " : "+ex.getMessage());
    }
        
    /** Sends response */
    public void sendResponse(String result)
    {
      try
      {
        if (returnHTML())
          writeHTMLResponse(result);
        else
          writeFunctionResponse(result);
      }
      catch(Exception ex)
      {
        out.println (ERROR);
      }
    }
    
    /** Write content in output web page */
    protected void writeFunctionResponse(String result) throws IOException, ServletException
    {
       out.println (result);
    }
    
    /** Write content in output web page */
    protected void writeHTMLResponse(String result) throws IOException, ServletException
    {
      out.println("<html>");
      out.println("<head>");

      out.println("<title>Thank You to use idbcrownINServer (by ITCrown, 2012)</title>");
      out.println("</head>");
      out.println("<body bgcolor=\"white\">");
      out.println("<body>");

      out.println("<h1>The result of your call is:</h1>");
      out.println (result);
      out.println("</body>");
      out.println("</html>");    
    }
 
    // Debug tools
    //
    /** Send mesage to debug output */
    protected void debug(String msg)
    {
      libFileDebug.getInstance().write("Function" + '.' + msg);
    }
    
   /**
   *  Escape the some entities defined by HTML.
   */
  public static String escapeHTML(String s)
  {
    if (s == null) return null;
    StringBuffer sb = new StringBuffer();
    for(int i=0; i<s.length(); i++) {
      char c = s.charAt(i);
      if (c == '<') {
	        sb.append("&lt;");
      } else if (c == '>') {
	        sb.append("&gt;");
      } else if (c == '&') {
	        sb.append("&amp;");
      } else if (c == '"') {
	        sb.append("&quot;");
      } else {
	        sb.append(c);
      }
    }
    return sb.toString();
  }

}